package com.example.nowcodercommunity.controller;

import com.example.nowcodercommunity.annotation.LoginRequire;
import com.example.nowcodercommunity.entity.LoginTicket;
import com.example.nowcodercommunity.entity.User;
import com.example.nowcodercommunity.service.CommunityConstant;
import com.example.nowcodercommunity.service.UserService;
import com.example.nowcodercommunity.util.CommunityUtil;
import com.example.nowcodercommunity.util.CookieUtil;
import com.example.nowcodercommunity.util.RedisKeyUtil;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.thymeleaf.util.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    // 创建日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 从yaml中读取作为上下文路径
     */
    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**
     * 访问注册页面
     * @return
     */
    @RequestMapping(path = "/register",method = RequestMethod.GET)
    public String getRegisterPage(){
        return "/site/register";
    }

    /**
     * 访问登录页面
     * @return
     */
    @RequestMapping(path = "/login",method = RequestMethod.GET)
    public String getLoginPage(){
//        System.out.println("LOGIN");
        return "/site/login";
    }

    /**
     * 注册用户
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public String register(Model model, User user){
        Map<String,Object> map = userService.register(user);
        if(map==null || map.isEmpty()){
            model.addAttribute("msg","注册成功，我们已向您的邮箱发送了一封激活邮件");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        } else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("mailMsg",map.get("mailMsg"));
            return "/site/register";
        }
    }

    /**
     * 激活用户账户
     * @param model
     * @param userId
     * @param code
     * @return
     */
    @RequestMapping(path = "/activation/{userId}/{code}", method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId,@PathVariable("code") String code){
        int result = userService.activation(userId, code);
        if(result == CommunityConstant.ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功！您的账号可以使用了");
            model.addAttribute("target","/login");
        }else if(result == CommunityConstant.ACTIVATION_REPEAT){
            model.addAttribute("msg","无效操作，该账号已激活");
            model.addAttribute("target","/index");
        }else{
            model.addAttribute("msg","激活失败，请检查激活码与账户");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }

//    /**
//     * 生成验证码并存入Session
//     * 每次进入登录页面时访问，效率低下且存在Session分布式共享问题，故废弃
//     * @param response
//     * @param session
//     * @throws IOException
//     */
//    @Deprecated
//    @RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
//    public void getKaptcha(HttpServletResponse response, HttpSession session) throws IOException {
//        String text = kaptchaProducer.createText();
//        BufferedImage image = kaptchaProducer.createImage(text);
//
//        session.setAttribute("kaptcha",text);
//
//        response.setContentType("image/png");
//        try {
//            ServletOutputStream os = response.getOutputStream();
//            ImageIO.write(image,"png",os);
//        }catch (IOException e){
//            logger.error("响应验证码失败"+e.getMessage());
//        }
//    }

    /**
     * 通过Cookie给客户端颁发临时凭证，并将该凭证用于Redis Key
     * 将Kaptcha生成的验证码装入Redis进行缓存(60秒超时)
     * 通过Kaptcha生成验证码图片并将Cookie数据和图片一并由Response带回
     * @param response
     */
    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response){
        String kaptcha = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(kaptcha);

        String tempoTicket = CommunityUtil.generateUUID();
        Cookie c = new Cookie("tempoTicket", tempoTicket);
        c.setMaxAge(60);
        c.setPath(contextPath);

        response.addCookie(c);

        String kaptchaKey = RedisKeyUtil.getKaptchaKey(tempoTicket);
        redisTemplate.opsForValue().set(kaptchaKey, kaptcha, 60, TimeUnit.SECONDS);

        response.setContentType("image/png");
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(image,"png",os);
        }catch (IOException e){
            logger.error("响应验证码失败"+e.getMessage());
        }
    }

    /**
     * 登录时具体处理
     * 首先通过请求中携带的Cookie结合Kaptcha获取其在Redis中的Key，并查询Redis中的验证码，校验验证码是否正确
     * 验证完毕后通过Service层中的Login()方法登录
     * @param model
     * @param response
     * @param tempoTicket
     * @param username
     * @param password
     * @param code
     * @param rememberMe
     * @return
     */
    @RequestMapping(path = "/login",method = RequestMethod.POST)
    public String Login(Model model, HttpServletResponse response, @CookieValue(name = "tempoTicket") String tempoTicket,
                        String username, String password, String code, boolean rememberMe){
        // 验证码校验
        String kaptcha = null;
        if(!StringUtils.isEmpty(tempoTicket)){
            String kaptchaKey = RedisKeyUtil.getKaptchaKey(tempoTicket);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }

        if(StringUtils.isEmpty(kaptcha) || StringUtils.isEmpty(code) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码错误！");
            return "/site/login";
        }

        // 登录凭证处理
        int expireTime = rememberMe ? CommunityConstant.REMEMBER_EXPIRE_SECONDS : CommunityConstant.DEFAULT_EXPIRE_SECONDS;
        Map<String,Object> map = userService.Login(username,password,expireTime);
        if(map.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expireTime);
            response.addCookie(cookie);

            return "redirect:/index";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));

            return "/site/login";
        }

    }

    /**
     * 用户登出，将登录状态票据状态改为过期即可
     * @param request
     * @return
     */
    @LoginRequire
    @RequestMapping(path = "/logout",method = RequestMethod.GET)
    public String Logout(HttpServletRequest request){
        String ticket = CookieUtil.getValue(request,"ticket");
        if(StringUtils.isEmpty(ticket)){
            throw new RuntimeException("登录状态异常！无法获取登录状态");
        }
        userService.updateTicketStatus(ticket,1);

        return "redirect:/index";
    }
}
